import React, { Component } from 'react'
import ReactDOMServer from 'react-dom/server';
import { connect } from 'dva';
import LeftSider from '@/components/LeftSider'
import BizIcon from '@/components/BizIcon'
import { formatMessage } from 'umi-plugin-locale'
import { Radio, Modal, Form, Input, DatePicker, Button, Slider, Checkbox, Tooltip, Table } from 'antd';
import { setFullScreen } from '@/utils/utils'
import moment from 'moment';
import KMap from '@/utils/KMap'

import styles from './index.less'

const { RangePicker } = DatePicker;
const map = window.localStorage.getItem('MAP')
const tilesHost = window.localStorage.getItem('MAP_TILES_HOST')
const secretKey = window.localStorage.getItem('MAP_SECRET_KEY')

@connect(({ device, config, loading }) => ({
    device,
    config,
    loading: loading.models.device,
}))
class Trace extends Component {

    columns = [
        {
            title: `${formatMessage({'id':'common.time'})}`,
            dataIndex: 'time',
            key: 'time',
            width: 170,
            defaultSortOrder: 'descend',
            sorter: (a, b) => moment(a.time) - moment(b.time),
            render: (text) => {
                return (
                    <>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</>
                )
            }
        },
        {
            title: `${formatMessage({"id":"common.lng_lat"})}`,
            dataIndex: 'lng',
            key: 'lng',
            width: 140,
            render: (text, record) => {
                return (
                    <>
                        <div>
                        {formatMessage({"id":"common.lng"})}: {record.lng}
                        </div>
                        <div>
                        {formatMessage({"id":"common.lat"})}: {record.lat}
                        </div>
                    </>
                )
            }
        },
        {
            title: `${formatMessage({"id":"common.address"})}`,
            dataIndex: 'addr',
            key: 'addr',
        }
    ];

    // 轨迹回放类的对象
    trace;

    state = {
        mapCfg: {
            zoom: 15,
            minZoom: 1,
            maxZoom: 19,
            center: {
                lng: 104.06751612201126,
                lat: 30.55540009918001
            },
            mapStyle: 'normal',
            tileLayerUrl: tilesHost,
            secretKey: secretKey,
            showExtraLayer: false
        },
        loading: false,
        currentAction: 'move',
        autoViewPort: true,
        pause: false,
        playEnd: false,
        showTrace: false,
        traceSpeed: 1,
        rangeTime: [moment().startOf('day'), moment().endOf('day')],
        traceList: [],
        expand: false
    }
    formRef = React.createRef();
    componentDidMount() {
        this.props.dispatch({
            type: 'config/fetch',
            callback: (res) => {
                this.setState({
                    mapCfg: {
                        ...this.state.mapCfg,
                        zoom: res.mapZoom || this.state.mapCfg.zoom,
                        center: {
                            lng: parseFloat(res.mapCenterLng) || this.state.mapCfg.center.lng,
                            lat: parseFloat(res.mapCenterLat) || this.state.mapCfg.center.lat,
                        }
                    },
                    traceSpeed: res.traceSpeed
                }, () => {
                    this.initMap();
                })
            }
        })
        this.formRef.current.setFieldsValue({
            rangeTime: [moment().startOf('day'), moment().endOf('day')]
            // rangeTime: [moment('2020-10-30 00:00:00'), moment('2020-10-30 23:00:00')]
        })

    }
    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }

    initMap = () => {
        this.map = new KMap('mapContainer', this.state.mapCfg)
    }
    changeMapStyle = (e) => {
        this.map.setMapStyle(e.target.value)
    }

    mapAction(action = 'move') {
        this.setState({
            currentAction: action
        })
        switch (action) {
            case 'move':
                this.map.move()
                break;
            case 'distance':
                this.map.distance()
                break;
            case 'zoomOut':
                this.map.boxZoomOut()
                break;
            case 'zoomIn':
                this.map.boxZoomIn()
                break;
            default:
                this.map.move()
        }
    }
    setFullscreen = () => {
        setFullScreen(this.mapView);
    }
    onSelect(node) {
        this.setState({
            deviecSn: node.sn
        }, () => {
            this.formRef.current.setFieldsValue({
                realname: node.title,
                deviceSn: node.sn,
            })
        })
    }
    onDoubleClick(selectedKeys, item) {

    }
    searchTrace() {
        this.formRef.current.validateFields().then(values => {
            let sn = values.deviceSn,
                startTime = values.rangeTime[0],
                endTime = values.rangeTime[1];

            if (!sn) {
                Modal.error({
                    title: `${formatMessage({'id':'trace.device_sn_invalid'})}`
                })
            } else if (endTime.diff(startTime, 'hours') > 24) {
                Modal.error({
                    title: `${formatMessage({'id':'trace.search_in_24_hours'})}`
                })
                return;
            } else {
                this.setState({ loading: true })
                startTime = startTime.format("YYYY-MM-DD HH:mm:ss")
                endTime = endTime.format("YYYY-MM-DD HH:mm:ss")
                this.props.dispatch({
                    type: 'device/fetchTrace',
                    payload: {
                        sn, startTime, endTime,
                        from: 'location'
                    },
                    callback: res => {
                        this.props.dispatch({
                            type: 'device/fetchDeviceInfo',
                            payload: {
                                sn
                            },
                            callback: deviceInfo => {
                                this.setState({
                                    traceList: res.data,
                                    loading: false
                                })
                                this.startTrace(res.data, deviceInfo.data)
                            }
                        })
                    }
                })
                this.setState({ loading: false })
            }
        })

    }
    startTrace(points, deviceInfo) {
        if (this.trace) {
            this.trace.stop();
        }
        let photo = deviceInfo.photo || "/images/baidu_police.png"
        let traceOptions = {
            strokeWeight: 2,
            strokeColor: '#569afc',
            movedLineStrokeColor: '#90ee90',
            showIcon: true,
            startIcon: '/images/start.png?v=1',
            endIcon: '/images/end.png?v=1',
            speed: this.state.traceSpeed,
            autoViewPort: this.state.autoViewPort,
            overlay: {
            },
            onPlaying: idx => {
                // console.log(idx)
            },
            onEndPlay: () => {
                this.setState({
                    playEnd: true
                }, () => {
                    this.trace.stop();
                })

            }
        };
        if (map === 'esri') {
            traceOptions.overlay.icon = window.KMap.Icons.ICON_POLICE;
            traceOptions.overlay.label = {
                showBg: true,
                text: deviceInfo.realname,
                size: '12px',
                color: [255, 255, 255],
            }
            traceOptions.overlay.offset = {
                x: 0,
                y: 24
            }
        }
        if (map === 'baidu_online' || map === 'baidu_offline') {
            // traceOptions.overlay.icon = window.KMap.Icons.ICON_POLICE;
            traceOptions.overlay.offset = {
                x: -65,
                y: -62
            }
            traceOptions.overlay.content = ReactDOMServer.renderToString(
                <div className={styles.avatarOverlay}>
                    <img alt="" src={photo} />
                    <div className={styles.content}>
                        <div className={styles.name}>{deviceInfo.realname}</div>
                        <div className={styles.policeNo}>{deviceInfo.policeNo}</div>
                    </div>
                </div>
            );
        } 
        if (map === 'supermap') {
            traceOptions.overlay.icon = window.KMap.Icons.ICON_POLICE;
            
            traceOptions.overlay.offset = {
                x: 0,
                y: 24
            }
        }
        this.trace = this.map.trace(points, traceOptions)
        setTimeout(() => {
            this.trace.start()
        }, 1000)
        this.setState({
            showTrace: true
        })
    }
    onChangeDate(values) {
        this.setState({
            rangeTime: values
        })
    }
    getDeviceInfo(deviceId) {
        this.props.dispatch({
            type: 'device/fetchDeviceInfo',
            payload: {
                id: deviceId
            }
        })
    }
    changeSpeed(value) {
        this.setState({
            traceSpeed: value
        }, () => {
            this.trace.setSpeed(value)
        })
    }
    replay() {
        this.trace.replay()
    }

    pause() {
        this.setState({
            pause: true
        }, () => {
            this.trace.pause()
        })
    }
    play() {
        this.setState({
            pause: false
        }, () => {
            if (!this.state.playEnd) {
                this.trace.play()
            } else {
                this.trace.start()
            }
        })
    }
    changeViewPort(e) {
        this.setState({
            autoViewPort: e.target.checked
        }, () => {
            e.target.checked === true ? this.trace.enableViewPort() : this.trace.disableViewPort();
        })
    }
    disabledDate(current) {
        return current && current > moment().endOf('day');
    }
    showTraceList() {
        this.setState({
            expand: !this.state.expand
        })
    }

    render() {
        const { traceSpeed } = this.props.config.config
        return (
            <div className='wrapper'>

                <div className='left-sider'>
                    <LeftSider canDisabled={false} onDoubleClick={this.onDoubleClick.bind(this)} onSelect={this.onSelect.bind(this)} />
                </div>
                <div className={styles.mapWrapper}>
                    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, height: '100%' }}>
                        <div className={styles.toolsBar}>
                            <Form layout={'inline'} ref={this.formRef}>

                                {/* <Form.Item label={formatMessage({'id':'trace.user'})} name="realname">
                                    <Input style={{ width: "150px" }} readOnly />
                                </Form.Item> */}
                                <Form.Item label={formatMessage({'id':'trace.device_sn'})} name="deviceSn">
                                    <Input style={{ width: "150px" }} />
                                </Form.Item>
                                <Form.Item label={formatMessage({'id':'trace.time_range'})} name="rangeTime">
                                    <RangePicker
                                        inputReadOnly
                                        showTime={{ format: 'HH:mm:ss' }}
                                        disabledDate={this.disabledDate}
                                        value={this.state.rangeTime}
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder={[formatMessage({ id: 'common.starttime' }), formatMessage({ id: 'common.endtime' })]}
                                        onChange={this.onChangeDate.bind(this)}
                                        allowClear={false}
                                    />
                                </Form.Item>
                                <Form.Item>
                                    <Button loading={this.state.loading} onClick={this.searchTrace.bind(this)} type="primary">{formatMessage({ id: 'common.button.search' })}</Button>
                                </Form.Item>
                            </Form>
                            <ul className={styles.toolsIcon}>
                                {/* <li className={this.state.currentAction === 'move' ? styles.active : ''} onClick={this.mapAction.bind(this, 'move')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-hand-paper" />
                                    <span>{formatMessage({ 'id': 'liveLocation.move' })}</span>
                                </li>
                                <li className={this.state.currentAction === 'zoomIn' ? styles.active : ''} onClick={this.mapAction.bind(this, 'zoomIn')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-zoom-in" />
                                    <span>{formatMessage({ 'id': 'liveLocation.zoomIn' })}</span>
                                </li>
                                <li className={this.state.currentAction === 'zoomOut' ? styles.active : ''} onClick={this.mapAction.bind(this, 'zoomOut')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-zoom-out" />
                                    <span>{formatMessage({ 'id': 'liveLocation.zoomOut' })}</span>
                                </li> */}
                                {
                                    map === 'baidu' && (
                                        <li className={this.state.currentAction === 'distance' ? styles.active : ''} onClick={this.mapAction.bind(this, 'distance')}>
                                            <BizIcon className={styles.toolsIcon} type="icon-distance" />
                                            <span>{formatMessage({ 'id': 'liveLocation.distance' })}</span>
                                        </li>
                                    )
                                }

                                <li onClick={this.setFullscreen.bind(this)}>
                                    <BizIcon className={styles.toolsIcon} type="icon-fullscreen" />
                                    <span>{formatMessage({ 'id': 'liveLocation.fullscreen' })}</span>
                                </li>
                            </ul>
                        </div>

                        <div className={`flex ${styles.map}`} ref={node => this.mapView = node}>
                            {
                                map === 'baidu' && (
                                    <div style={{ position: 'absolute', top: '10px', right: '10px', zIndex: 1001 }}>
                                        <Radio.Group defaultValue="light" buttonStyle="solid" size="small" onChange={this.changeMapStyle}>
                                            <Radio.Button value="light">
                                                <BizIcon type="icon-taiyang" />
                                            </Radio.Button>
                                            <Radio.Button value="dark">
                                                <BizIcon type="icon-moon" />
                                            </Radio.Button>
                                        </Radio.Group>
                                    </div>
                                )
                            }
                            <div className="flex flex-item justify-content-between">
                                <div id="mapContainer" ref={this.mapRef} className="flex-item"></div>

                            </div>
                            <div className={`${styles.traceList} ${this.state.expand ? styles.expand : ''}`}>
                                <Table
                                    style={{ height: '100%' }}
                                    bordered
                                    size="small"
                                    scroll={{ y: 'calc(100vh - 200px)' }}
                                    // loading={this.state.loading}
                                    rowKey={record => record.time}
                                    columns={this.columns}
                                    dataSource={this.state.traceList}
                                    pagination={{
                                        defaultPageSize: 50,
                                        showSizeChanger: true,
                                        showTotal: total => {
                                            return `共 ${total} 条记录`;
                                        }
                                    }}
                                />
                            </div>


                            {
                                this.state.showTrace && <div className={styles.mapTools}>
                                    <ul>
                                        <li>
                                            {
                                                !this.state.pause && !this.state.playEnd ?
                                                    (<Tooltip title={formatMessage({'id':'trace.pause'})}>
                                                        <Button type="link" onClick={this.pause.bind(this)} icon={<BizIcon type="icon-pause" style={{ fontSize: '28px' }} />}></Button>
                                                    </Tooltip>)
                                                    : (<Tooltip title={formatMessage({'id':'trace.play'})}>
                                                        <Button type="link" onClick={this.play.bind(this)} icon={<BizIcon type="icon-play" style={{ fontSize: '28px' }} />}></Button>
                                                    </Tooltip>)
                                            }
                                        </li>
                                        <li>
                                            <Tooltip title={formatMessage({'id':'trace.replay'})}>
                                                <Button type="link" onClick={this.replay.bind(this)} icon={<BizIcon type="icon-trace-replay" style={{ fontSize: '28px' }} />}></Button>
                                            </Tooltip>
                                        </li>
                                    </ul>
                                    <div className={styles.traceSpeed}>
                                        <div className={styles.traceLabel}>
                                        {formatMessage({'id':'trace.play_speed'})}
                                        </div>
                                        <div className={styles.traceBar}>
                                            <Slider tooltipVisible={false} min={1} max={50} defaultValue={traceSpeed} onChange={this.changeSpeed.bind(this)} />
                                        </div>
                                    </div>
                                    <div style={{ paddingRight: '10px' }}>
                                        [ {this.state.traceSpeed} ]
                                    </div>
                                    <div>
                                        <Checkbox
                                            checked={this.state.autoViewPort}
                                            onChange={this.changeViewPort.bind(this)}
                                        >
                                            {formatMessage({'id':'trace.viewport'})}
                                        </Checkbox>
                                    </div>
                                    <div>
                                        <Tooltip title={!this.state.expand ? formatMessage({'id':'trace.expand_trace_list'}) : formatMessage({'id':'trace.collapse_trace_list'})}>
                                            <Button type="link" onClick={this.showTraceList.bind(this)} icon={!this.state.expand ? (<BizIcon type="icon-zhankai" style={{ fontSize: '22px' }} />) : (<BizIcon type="icon-shouqi" style={{ fontSize: '22px' }} />)}></Button>
                                        </Tooltip>
                                    </div>
                                </div>
                            }


                        </div>
                    </div>
                </div>
            </div >
        )
    }
}
export default Trace